//
//  SRSportService.m
//  SportRing
//
//  Created by Apple on 14/10/29.
//  Copyright (c) 2014年 HotOne. All rights reserved.
//

#import "SRSportNetService.h"
#import "SRSportNetSource.h"
#import "SRDB.h"

@implementation SRSportNetService

+ (RACSignal *)uploadSportPart:(SRSportPart *)part
{
    RACSubject * subject = [RACSubject subject];
    SRMe * me = [SRMe currentUser];
    [SRSportNetSource addRecordCounterWithToken:me.token
                                        section:part.section.intValue
                                     runCounter:part.runCounter.intValue
                                upstairsCounter:part.upstairsCounter.intValue
                                    walkCounter:part.walkCounter.intValue
                                        calorie:part.calorie.intValue
                                             T1:part.t1.intValue
                                             T2:part.t2.intValue
                                             T3:part.t3.intValue
                                             T4:part.t4.intValue
                                        mileage:part.mileage.intValue
                                     createDate:part.day.createDate
                                        success:^(NSDictionary *dict)
     {
         if ([dict[@"code"] intValue] == 0)
         {
             [part configAttributesWithBlock:^(SRSportPart *aSelf) {
                 aSelf.isSynced = @(YES);
             }];
             [subject sendNext:nil];
         }
         else
         {
             [subject sendError:[NSError errorWithDomain:@"error"
                                                    code:[dict[@"code"] intValue]
                                                userInfo:@{@"tip":dict[@"tip"]}]];
         }
     }
                                        failure:^(NSError *error)
     {
         [subject sendError:error];
     }];
    
    return subject;
}

//获取月步数据统计
+ (RACSignal *)getStatisticsForMonth:(NSString *)monthStr
{
    RACSubject * subject = [RACSubject subject];
    SRMe * me = [SRMe currentUser];
    [SRSportNetSource getStatisticsByMonthCounterWithToken:me.token
                                                     month:monthStr
                                                   success:^(NSDictionary *dict)
     {
         if ([dict[@"code"] intValue] == 0)
         {
             SRMe *me = [SRMe currentUser];
             NSDate *date = [NSDate dateFromString:monthStr format:@"yyyy-MM"];
             SRMonth *month = [SRMonth findMonthCINEForMonthStr:[date formattedBy_yyyyMM] forMe:me];
             [month configAttributesWithBlock:^(SRMonth *aSelf) {
                 aSelf.counter = @([dict[@"data"][@"walkCounter"] intValue]);
                 aSelf.mileage = @([dict[@"data"][@"Mileage"] intValue]);
                 aSelf.calorie = @([dict[@"data"][@"Calorie"] intValue]);
             }];
             
             [subject sendNext:month];
         }
         else
         {
             [subject sendError:[NSError errorWithDomain:@"error"
                                                    code:[dict[@"code"] intValue]
                                                userInfo:@{@"tip":dict[@"tip"]}]];
         }
     }
                                                   failure:^(NSError *error)
     {
         [subject sendError:error];
     }];
    
    return subject;
}

+ (void)getStatisticsForMonth:(NSString *)monthStr withSuccess:(CompletionBlockWithDictionary)success fail:(CompletionBlockWithError)fail {
    
    NSDate *date = [NSDate dateFromString:monthStr format:@"yyyy-MM"];
    [SRSportNetSource getStatisticsByMonthCounterWithToken:[SRMe currentUser].token
                                                     month:[date formattedBy_yyyyMM]
                                                   success:success
                                                   failure:fail];
}

//获取指定月的每天数据
//+ (RACSignal *)getDaySportForMonth:(NSString *)monthStr
//{
//    RACSubject * subject = [RACSubject subject];
//    SRMe * me = [SRMe currentUser];
//    [SRSportNetSource getDaySportForMonthWithToken:me.token
//                                             month:monthStr
//                                           success:^(NSDictionary *dict)
//     {
//         if ([[dict objectForKey:@"code"] intValue] == 0)
//         {
//             NSArray *array = dict[@"data"];
//             NSDate *date = [NSDate dateFromString:monthStr format:nil];
//             SRMonth *month = [SRMonth findMonthCINEForMonthStr:[date formattedBy_yyyyMM] forMe:me];
//             [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
//                 NSDictionary * dataDict = obj;
//                 NSDate * createDate = [NSDate dateFromString:dataDict[@"createDate"]];
//                 SRDay *day = [SRDay findDayCINEForDateStr:[createDate formattedBy_yyyyMMdd] forMe:me];
//                 [day configAttributesWithBlock:^(SRDay *aSelf) {
//                     aSelf.counter = @([dataDict[@"Counter"] intValue]);
//                     aSelf.calorie = @([dataDict[@"Calorie"] intValue]);
//                     aSelf.mileage = @([dataDict[@"Mileage"] intValue]);
//                 }];
//             }];
//             [subject sendNext:month];
//         }
//         else
//         {
//             [subject sendError:[NSError errorWithDomain:@"error"
//                                                    code:[dict[@"code"] intValue]
//                                                userInfo:@{@"tip":dict[@"tip"]}]];
//         }
//     }
//                                           failure:^(NSError *error)
//     {
//         [subject sendError:error];
//     }];
//    
//    return subject;
//}

+ (void)getDaySportForMonth:(NSString *)monthStr withSuccess:(CompletionBlockWithDictionary)success fail:(CompletionBlockWithError)fail {
    
    NSDate *date = [NSDate dateFromString:monthStr format:@"yyyy-MM"];
    
    [SRSportNetSource getDaySportForMonthWithToken:[SRMe currentUser].token
                                            yyyyMM:[date formattedBy_yyyyMM]
                                           success:success failure:fail];
}

//获取天计步数据
+ (RACSignal *)getDaySportWithDate:(NSString *)date
{
    RACSubject * subject = [RACSubject subject];
    SRMe * me = [SRMe currentUser];
    [SRSportNetSource getRecordByDateCounterWithToken:me.token
                                                 date:date
                                              success:^(id object)
     {
         SRDay * day = [SRDay findDayCINEForDateStr:date forMe:me];
         
         NSDictionary *dict = (NSDictionary*)object;
         if ([[dict objectForKey:@"code"] intValue] == 0)
         {
             NSArray *sportData = [dict objectForKey:@"data"];
             if (sportData.count > 0) {
                 
                 NSMutableSet *sets = [[NSMutableSet alloc] init];
                 [sportData enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                     NSDictionary * dataDict = obj;
                     SRSportPart * sportPart = [SRSportPart findSportPartCINEForDay:day forSection:[dataDict[@"section"] intValue]];
                     [sportPart configAttributesWithBlock:^(SRSportPart *aSelf) {
                         sportPart.runCounter = @([dataDict[@"runCounter"] intValue]);
                         sportPart.upstairsCounter = @([dataDict[@"upstairsCounter"] intValue]);
                         sportPart.walkCounter = @([dataDict[@"walkCounter"] intValue]);
                         sportPart.calorie = @([dataDict[@"calorie"] intValue]);
                         sportPart.t1 = @([dataDict[@"T1"] intValue]);
                         sportPart.t2 = @([dataDict[@"T2"] intValue]);
                         sportPart.t3 = @([dataDict[@"T3"] intValue]);
                         sportPart.t4 = @([dataDict[@"T4"] intValue]);
                         sportPart.mileage = @([dataDict[@"mileage"] intValue]);
                         sportPart.isSynced = @YES;//表示数据已经同步到服务器
                     }];
                     [sets addObject:sportPart];
                 }];
                 
                 day.sportParts = sets;
             }
             
             [subject sendNext:day];
         }
         else
         {
             [subject sendError:[NSError errorWithDomain:@"error"
                                                    code:[dict[@"code"] intValue]
                                                userInfo:@{@"tip":dict[@"tip"]}]];
         }
         
     }
                                              failure:^(NSError *error)
     {
         [subject sendError:error];
     }];
    
    return subject;
}

//上传计步任务数据

+ (RACSignal *)uploadTask:(SRSportTask *)task
{
    RACSubject * subject = [RACSubject subject];
    SRMe * me = [SRMe currentUser];
    [SRSportNetSource addTaskWithToken:me.token
                            createDate:task.day.createDate
                             startTime:task.startTime
                               endTime:task.endTime
                          totalCounter:task.totalCounter.intValue
                      completedCounter:task.completedCounter.intValue
                               success:^(NSDictionary *dict)
     {
         if ([[dict objectForKey:@"code"] intValue] == 0)
         {
             [task configAttributesWithBlock:^(SRSportTask *aSelf) {
                 aSelf.isSynced = @(YES);
             }];
             [subject sendNext:nil];
             
         }
         else
         {
             [subject sendError:[NSError errorWithDomain:@"error"
                                                    code:[dict[@"code"] intValue]
                                                userInfo:@{@"tip":dict[@"tip"]}]];
         }
     }
                               failure:^(NSError *error)
     {
         [subject sendError:error];
     }];
    
    return subject;
}

//获取月计步任务统计
+ (RACSignal *)getTaskStatisticsByMonth:(NSString *)monthStr
{
    RACSubject * subject = [RACSubject subject];
    SRMe * me = [SRMe currentUser];
    [SRSportNetSource getTaskStatisticsWithToken:me.token
                                           month:monthStr
                                         success:^(NSDictionary *dict)
     {
         if ([[dict objectForKey:@"code"] intValue] == 0)
         {
             NSDate * date = [NSDate dateFromString:monthStr format:nil];
             SRSportTask * task = [SRSportTask findTaskCINEForMonth:[date formattedBy_yyyyMM]];
             [task configAttributesWithBlock:^(SRSportTask *aSelf) {
                 aSelf.totalCounter = @([dict[@"data"][@"totalCounter"] intValue]);
                 aSelf.completedCounter = @([dict[@"data"][@"completedCounter"] intValue]);
                 aSelf.isSynced = @YES;
             }];
             [subject sendNext:task];
         }
         else
         {
             [subject sendError:[NSError errorWithDomain:@"error"
                                                    code:[dict[@"code"] intValue]
                                                userInfo:@{@"tip":dict[@"tip"]}]];
         }
         
     }
                                         failure:^(NSError *error)
     {
         [subject sendError:error];
     }];
    
    return subject;
}

//获取天计步任务数据
+ (RACSignal *)getTaskByDay:(NSString *)dayStr
{
    RACSubject * subject = [RACSubject subject];
    SRMe * me = [SRMe currentUser];
    [SRSportNetSource getTaskByDayWithToken:me.token
                                       date:dayStr
                                    success:^(NSDictionary *dict)
     {
         if ([[dict objectForKey:@"code"] intValue] == 0)
         {
             if ([dict[@"data"] isKindOfClass:[NSNull class]]) {
                 [subject sendNext:nil];
             }
             else
             {
                 SRSportTask * task = [SRSportTask findTaskCINEForDay:dayStr];
                 [task configAttributesWithBlock:^(SRSportTask *aSelf) {
                     aSelf.totalCounter = @([dict[@"data"][@"totalCounter"] intValue]);
                     aSelf.completedCounter = @([dict[@"data"][@"completedCounter"] intValue]);
                     aSelf.startTime = dict[@"data"][@"startTime"];
                     aSelf.endTime = dict[@"data"][@"endTime"];
                     aSelf.isSynced = @YES;
                 }];
                 [subject sendNext:task];
             }
         }
         else
         {
             [subject sendError:[NSError errorWithDomain:@"error"
                                                    code:[dict[@"code"] intValue]
                                                userInfo:@{@"tip":dict[@"tip"]}]];
         }
         
     }
                                    failure:^(NSError *error)
     {
         [subject sendError:error];
     }];
    
    return subject;
}

+ (void)getTasksByDayWithStartDate:(NSString *)startDate endDate:(NSString *)endDate withSuccess:(CompletionBlockWithDictionary)success fail:(CompletionBlockWithError)fail {
    
    NSDate *start_date = [NSDate dateFromString:startDate format:@"yyyy-MM-dd"];
    NSDate *end_date = [NSDate dateFromString:endDate format:@"yyyy-MM-dd"];
    [SRSportNetSource getTasksByDayWithToken:[SRMe currentUser].token
                                   startDate:[start_date formattedBy_yyyyMMdd]
                                     endDate:[end_date formattedBy_yyyyMMdd]
                                     success:success
                                     failure:fail];
}

//上传睡眠数据
+ (RACSignal *)uploadSleepWithSleep:(SRSleep *)sleep;
{
    __block NSMutableArray * mArray = [NSMutableArray array];
    [sleep.sleepParts enumerateObjectsUsingBlock:^(id obj, BOOL *stop) {
        SRSleepPart * part = obj;
        NSMutableDictionary * mDict = [@{} mutableCopy];
        mDict[@"time"] = [part.time formattedBy_yyyyMMddhhmmss];
        mDict[@"shake"] = part.shake;
        [mArray addObject:mDict];
    }];
    
    RACSubject * subject = [RACSubject subject];
    SRMe * me = [SRMe currentUser];
    [SRSportNetSource uploadSleepWithToken:me.token
                                 startTime:[sleep.startTime formattedBy_yyyyMMddhhmmss]
                                   endTime:[sleep.endTime formattedBy_yyyyMMddhhmmss]
                                    sleeps:mArray
                                   success:^(NSDictionary *dict)
     {
         if ([[dict objectForKey:@"code"] intValue] == 0)
         {
             [sleep configAttributesWithBlock:^(SRSleep *aSelf) {
                 aSelf.isSynced = @(YES);
                 [SRSleep deleteSleepForDay:aSelf.day];
             }];
             [subject sendNext:nil];
             
         }
         else
         {
             [subject sendError:[NSError errorWithDomain:@"error"
                                                    code:[dict[@"code"] intValue]
                                                userInfo:@{@"tip":dict[@"tip"]}]];
         }
     }
                                   failure:^(NSError *error)
     {
         [subject sendError:error];
     }];
    
    return subject;
}

//获取天睡眠数据
+ (RACSignal *)getSleepForDay:(NSString *)dayStr
{
    RACSubject * subject = [RACSubject subject];
    SRMe * me = [SRMe currentUser];
    [SRSportNetSource getRecordSleepWithToken:me.token
                                         date:dayStr
                                      success:^(NSDictionary *dict)
     {
         if ([[dict objectForKey:@"code"] intValue] == 0)
         {
             SRDay * day = [SRDay findDayForDateStr:dayStr forMe:me];
             
             if (dict[@"data"] != nil)
             {
                 [SRSleep deleteSleepForDay:day];
                 
                 SRSleep * sleep = [SRSleep sleep];
                 [sleep configAttributesWithBlock:^(SRSleep *aSelf) {
                     aSelf.startTime = [NSDate dateFromString:dict[@"data"][@"startTime"] format:@"yyyy-MM-dd HH:mm:ss"];
                     aSelf.endTime = [NSDate dateFromString:dict[@"data"][@"endTime"] format:@"yyyy-MM-dd HH:mm:ss"];
                     aSelf.day = day;
                     aSelf.isSynced = @YES;//表示数据已经同步到服务器
                 }];
                 
                 NSArray * array = dict[@"data"][@"count"];
                 [array enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
                     NSDictionary * dataDict = obj;
                     SRSleepPart * part = [SRSleepPart partForSleep:sleep];
                     [part configAttributesWithBlock:^(SRSleepPart *aSelf) {
                         aSelf.timeStr = dataDict[@"time"];
                         NSString * timeStr = [NSString stringWithFormat:@"%@ %@", dayStr, aSelf.timeStr];
                         NSDate * date = [NSDate dateFromString:timeStr format:@"yyyy-MM-dd HH:mm:ss"];
                         aSelf.time = date;
                         aSelf.shake = @([dataDict[@"shake"] intValue]);
                     }];
                 }];
             }
             [subject sendNext:day];
         }
         else
         {
             [subject sendError:[NSError errorWithDomain:@"error"
                                                    code:[dict[@"code"] intValue]
                                                userInfo:@{@"tip":dict[@"tip"]}]];
         }
         
     }
                                      failure:^(NSError *error)
     {
         [subject sendError:error];
     }];
    
    return subject;
}

//睡眠评估
+ (RACSignal *)evaluateSleepWithDuration:(int)duration
                                    rems:(int)rems
                                   nrems:(int)nrems
                                  wakeup:(int)wakeup
{
    RACSubject * subject = [RACSubject subject];
    SRMe * me = [SRMe currentUser];
    [SRSportNetSource evaluateSleepWithToken:me.token
                                    duration:duration
                                        rems:rems
                                       nrems:nrems
                                      wakeup:wakeup
                                     success:^(NSDictionary *dict)
     {
         if ([[dict objectForKey:@"code"] intValue] == 0)
         {
             [subject sendNext:dict[@"data"][@"guide"]];
             
         }
         else
         {
             [subject sendError:[NSError errorWithDomain:@"error"
                                                    code:[dict[@"code"] intValue]
                                                userInfo:@{@"tip":dict[@"tip"]}]];
         }
     }
                                     failure:^(NSError *error)
     {
         [subject sendError:error];
     }];
    
    return subject;
}

//运动评估
+ (RACSignal *)evaluateCounterWithCounter:(int)counter
                                  mileage:(int)mileage
                                  calorie:(int)calorie
{
    RACSubject * subject = [RACSubject subject];
    SRMe * me = [SRMe currentUser];
    [SRSportNetSource evaluateCounterWithToken:me.token
                                       counter:counter
                                       mileage:mileage
                                       calorie:calorie
                                       success:^(NSDictionary *dict)
     {
         if ([[dict objectForKey:@"code"] intValue] == 0)
         {
             [subject sendNext:dict[@"data"][@"guide"]];
             
         }
         else
         {
             [subject sendError:[NSError errorWithDomain:@"error"
                                                    code:[dict[@"code"] intValue]
                                                userInfo:@{@"tip":dict[@"tip"]}]];
         }
     }
                                       failure:^(NSError *error)
     {
         [subject sendError:error];
     }];
    
    return subject;
}

@end
